//
//  ViewController.swift
//  图片选择器
//
//  Created by WGP on 16/4/22.
//  Copyright © 2016年 WGP. All rights reserved.
//

import UIKit

private let reuseIdentifier = "cell"

class HMPhotoSelectorController: UICollectionViewController{

//    记录用户选择的图片
    var photos = [UIImage]()
    
    private var maxCount = 6
    
    private var layout = UICollectionViewFlowLayout()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        layout.itemSize = CGSize(width: 80, height: 80)
        collectionView?.registerClass(HMPhotoSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        collectionView?.backgroundColor = UIColor.whiteColor()
        collectionView?.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 0, right: 10)
        
    }
    
    init()
    {
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return photos.count < maxCount ? photos.count + 1 : maxCount
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! HMPhotoSelectorCell
        cell.backgroundColor = UIColor.brownColor()
        
        cell.delegate = self
        
        if indexPath.item < photos.count
        {
            cell.image = photos[indexPath.item]
        }else
        {
            cell.setupAddButton()
        }
        
        return cell
    }

}

extension HMPhotoSelectorController: HMPhotoSelectorCellDelegate
{
    func photoSelectorCellDidClickAddButton(cell: HMPhotoSelectorCell) {
        
//        系统有一个照片选折起
        let pickerVC = UIImagePickerController()
        
        pickerVC.delegate = self
        
        presentViewController(pickerVC, animated: true, completion: nil)
    }
    
    func photoSelectorCellDidClickDeleteButton(cell: HMPhotoSelectorCell) {
        
//        获取cell的indexPath
        let indexPath = collectionView?.indexPathForCell(cell)
//        删除图片
        photos.removeAtIndex(indexPath!.item)
        
        collectionView?.reloadData()
    }
}

extension HMPhotoSelectorController: UIImagePickerControllerDelegate,UINavigationControllerDelegate
{
    //        当选中图片之后就会调用这个代理方法
    //        当实现这个代理协议,需要我们自己来关闭控制器
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        let newWidth: CGFloat = 300
        let newHeight = newWidth * image.size.height / image.size.width
        
        image.hm_AsyncDrawImage(CGSize(width: newWidth, height: newHeight)) { (image) -> () in
            
            self.photos.append(image)
            self.collectionView?.reloadData()
            
            picker.dismissViewControllerAnimated(true, completion: nil)
        }
    }
}


protocol HMPhotoSelectorCellDelegate: NSObjectProtocol
{
    func photoSelectorCellDidClickAddButton(cell: HMPhotoSelectorCell)
    func photoSelectorCellDidClickDeleteButton(cell: HMPhotoSelectorCell)
}

class HMPhotoSelectorCell: UICollectionViewCell {
    
    weak var delegate: HMPhotoSelectorCellDelegate?
    
    var image: UIImage?
    {
        didSet
        {
//            将图片设置给家好按钮
            addButton.setImage(image, forState: .Normal)
            
//            显示删除按钮
            deleteButton.hidden = false
        }
    }
    
//    设置加号按钮
    func setupAddButton()
    {
        addButton.setImage(UIImage(named: "compose_pic_add"), forState: .Normal)
        
//        隐藏删除按钮
        deleteButton.hidden = true
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    private func setupUI()
    {
//        添加空间
        contentView.addSubview(addButton)
        contentView.addSubview(deleteButton)
        
//        添加约束
        addButton.translatesAutoresizingMaskIntoConstraints = false
        deleteButton.translatesAutoresizingMaskIntoConstraints = false
        
//        VFL
//        加号按钮填充父控件
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[ab]-0-|", options: [], metrics: nil, views: ["ab":addButton]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[ab]-0-|", options: [], metrics: nil, views: ["ab":addButton]))
//        删除按钮,父控件右上角
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[db]-0-|", options: [], metrics: nil, views: ["db":deleteButton]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[db]", options: [], metrics: nil, views: ["db":deleteButton]))
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc private func didClickDeleteButton()
    {
        delegate?.photoSelectorCellDidClickDeleteButton(self)
    }
    
    @objc private func didClickAddButton()
    {
        delegate?.photoSelectorCellDidClickAddButton(self)
    }
    
    //    MARK: - 懒加载
    private lazy var deleteButton: UIButton =
    {
        let button = UIButton()
        
        //        设置
        button.setImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        button.addTarget(self, action: Selector("didClickDeleteButton"), forControlEvents: .TouchUpInside)
        
        return button
    }()
    
    private lazy var addButton: UIButton =
    {
        let button = UIButton()
        
        //        设置
        button.setImage(UIImage(named: "compose_pic_add"), forState: .Normal)
        //        设置图片的填充模式
        button.imageView?.contentMode = .ScaleAspectFill
        
        button.addTarget(self, action: Selector("didClickAddButton"), forControlEvents: .TouchUpInside)
        
        return button
    }()
}

